import SysUtils from './utils/SysUtil'
import { ipcRenderer } from 'electron'
import { defaultHt as dht, mainFontColor} from './common'

const memCalc = 1024 * 1024 * 1024
const memCalc2 = 1024 * 1024
const memCalc3 = 1024
const defaultHt = 215
let contentHt = 0

/**
 * 获取联动内存、压缩内存
 * @param setMemOther
 */
const topInfo = (setMemOther) => {
  if (process.platform === 'win32') {
    setMemOther([0, 0])
  } else {
    const { spawn } = require('child_process')
    const top = spawn('top', [' -n 1 | head -n 10'], { shell: true })
    top.stdout.on('data', (data) => {
      const dt = data.toString()
      let startIdx = dt.indexOf('PhysMem')
      let endIdx = dt.indexOf('unused.')
      let mem = dt.substring(startIdx, endIdx)
      startIdx = mem.indexOf('(')
      endIdx = mem.indexOf(')')
      // ['2493M wired', ' 64K compressor']
      const mems = mem.substring(startIdx + 1, endIdx).split(',')
      // console.log(mems)
      if (mems.length === 1) {
        mems[1] = '- MB'
      }
      mems.forEach((item, index) => {
        const im = mems[index].replace(/^\s+|\s+$/g, '')
        const numStr = im.split(' ')[0]
        let num = 0
        let flag = 0
        if (numStr.lastIndexOf('G') > 0) {
          num = numStr.replace('G', '')
          mems[index] = num
        } else if (numStr.lastIndexOf('M') > 0) {
          num = numStr.replace('M', '')
          flag = memCalc3
        } else if (numStr.lastIndexOf('K') > 0) {
          num = numStr.replace('K', '')
          flag = memCalc2
        } else if (numStr.lastIndexOf('B') > 0) {
          // num = numStr.replace('B', '')
          mems[index] = 0
        }
        if (flag !== 0) {
          mems[index] = numChange(num, flag)
        }
      })
      setMemOther([...mems])
      // console.log(mems)
    })
  }
}

const numChange = (num, rate) => {
  let intPart = Math.floor(Number(num) / rate)
  let floatPart = Number(num) % rate
  return Number(`${intPart}.${floatPart}`).toFixed(2)
}

/**
 * 内存信息
 * @param info 见getMemInf
 * @returns {Promise<void>}
 */
const memInfo = async (info) => {
  const detail = await SysUtils.memDetail()
  detail.forEach((item) => {
    item.size = (item.size / memCalc).toFixed(0)
  })
  if (detail.length > 1) {
    contentHt = detail.length * 85 + defaultHt + 15
  } else {
    contentHt = defaultHt
  }
  // console.log(detail)
  return new Promise((resolve) => {
    info.detail = detail
    info.contentHt = contentHt
    // console.log(info)
    resolve(info)
  })
}

/**
 * 获取内存信息
 * @returns {Promise<unknown>}
 */
const getMemInf = async () => {
  const info = await SysUtils.memInfo()
  return new Promise((resolve) => {
    const data = {
      total: (info.total / memCalc).toFixed(0),
      free: (info.free / memCalc).toFixed(2),
      used: (info.used / memCalc).toFixed(2),
      active: (info.active / memCalc).toFixed(2),
      buffcache: (info.buffcache / memCalc).toFixed(2),
      buffers: info.buffers,
      cached: info.cached,
      available: (info.available / memCalc).toFixed(2)
    }
    data.usage = Number(((Number(data.active) / Number(data.total)) * 100).toFixed(2))
    if (data.usage === 100) {
      data.usage = 100
    }
    window.topInfo[2] = data.usage
    // console.log(window.topInfo)
    resolve(data)
  })
}

/**
 * 获取图表option
 * @param t
 * @param memInf
 * @param memOther
 * @returns
 */
const getOption = (t, memInf, memOther) => {
  let active = 0
  let wired = 0
  let compressed = 0
  let available = 0
  if (memInf) {
    active = memInf.active ? memInf.active : 0
    available = memInf.available ? memInf.available : 0
  }
  if (memOther) {
    wired = memOther[0] ? memOther[0].split(' ')[0] : 0
    compressed = memOther[1] ? memOther[1].split(' ')[0] : 0
  }

  // console.log(`wired = ${ wired }`)
  // console.log(`compressed = ${ compressed }`)

  return {
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      top: 'center',
      textStyle: {
        fontSize: 12,
        color: mainFontColor
      }
    },
    color: ['#FAC858', '#5470C6', '#73C0DE', '#EF6666'],
    series: [
      {
        type: 'pie',
        data: [
          { value: active, name: `${t('active')}${active} GB`, label: { color: mainFontColor } },
          { value: wired, name: `${t('wired')}${wired} GB`, label: { color: mainFontColor } },
          { value: compressed, name: `${t('compressed')}${compressed} GB`, label: { color: mainFontColor } },
          { value: available, name: `${t('available')}${available} GB`, label: { color: mainFontColor } }
        ],
        center: ['82%', '50%'],
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
}

/**
 * 设置窗口高度
 * @param ht
 */
const setMemHt = (ht) => {
  if (ht > 0) {
    ipcRenderer.send('winHtChange', ht + dht)
  }
}

/**
 * 设置数据
 * @param props
 * @param setMemInf
 * @param setMemOther
 */
const setMem = (props, setMemInf, setMemOther) => {
  const data = props.data

  if (props.clickedItemIdx === 2) {
    memInfo({ ...data.memBaseInf }).then((data) => {
      setMemInf({ ...data })
      topInfo(setMemOther)
    })
  }
}

export { memInfo, topInfo, setMemHt, getOption, getMemInf, setMem }
